package com.distribution.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysDictData;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.utils.StringUtils;
import com.distribution.system.domain.entity.CmccDaUpChannelInfo;
import com.distribution.system.domain.req.CmccDaUpChannelInfoAddReq;
import com.distribution.system.domain.req.CmccDaUpChannelInfoListReq;
import com.distribution.system.domain.req.CmccDaUpChannelInfoUpdateReq;
import com.distribution.system.service.CmccDaOrderService;
import com.distribution.system.service.CmccDaUpChannelInfoService;
import com.distribution.system.service.ISysDictDataService;
import com.distribution.system.utils.convert.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: GodLu
 * @create: 2024-04-27 14:49
 * @description: 上游渠道信息控制器
 */
@RestController
@RequestMapping(value = "/CmccDaUpChannelInfo")
@Slf4j
public class CmccDaUpChannelInfoController extends BaseController {
    @Resource
    CmccDaUpChannelInfoService cmccDaUpChannelInfoService;
    @Resource
    ISysDictDataService sysDictDataService;
    @Resource
    CmccDaOrderService cmccDaOrderService;

    /**
    * @Author: GodLu
    * @Date: 2024/7/3 9:05
    * @Description: 查询上游渠道列表
    * @param cmccDaUpChannelInfoListReq 请求参数
    * @return: TableDataInfo
    */
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody CmccDaUpChannelInfoListReq cmccDaUpChannelInfoListReq) {
        startPage();
        LambdaQueryWrapper<CmccDaUpChannelInfo> queryWrapper = new LambdaQueryWrapper<CmccDaUpChannelInfo>()
                .eq(!Objects.isNull(cmccDaUpChannelInfoListReq.getChannelId()), CmccDaUpChannelInfo::getChannelId, cmccDaUpChannelInfoListReq.getChannelId())
                .like(!StringUtils.isEmpty(cmccDaUpChannelInfoListReq.getChannelName()), CmccDaUpChannelInfo::getChannelName, cmccDaUpChannelInfoListReq.getChannelName())
                .eq(!Objects.isNull(cmccDaUpChannelInfoListReq.getStatus()), CmccDaUpChannelInfo::getStatus, cmccDaUpChannelInfoListReq.getStatus())
                .like(!StringUtils.isNull(cmccDaUpChannelInfoListReq.getRemark()), CmccDaUpChannelInfo::getRemark, cmccDaUpChannelInfoListReq.getRemark());
        if (!Objects.isNull(cmccDaUpChannelInfoListReq.getBeginTime())) {
            queryWrapper.ge(CmccDaUpChannelInfo::getCreateTime, cmccDaUpChannelInfoListReq.getBeginTime());
        }
        if (!Objects.isNull(cmccDaUpChannelInfoListReq.getEndTime())) {
            queryWrapper.le(CmccDaUpChannelInfo::getCreateTime,cmccDaUpChannelInfoListReq.getEndTime());
        }
        queryWrapper.orderByDesc(CmccDaUpChannelInfo::getCreateTime);
        List<CmccDaUpChannelInfo> cmccDaUpChannelInfoList = cmccDaUpChannelInfoService.list(queryWrapper);
        return getDataTable(cmccDaUpChannelInfoList);
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated CmccDaUpChannelInfoAddReq cmccDaUpChannelInfoAddReq) {
//        System.out.println("cmccDaUpChannelInfoAddReq = " + cmccDaUpChannelInfoAddReq);
        CmccDaUpChannelInfo cmccDaUpChannelInfo = new CmccDaUpChannelInfo();
        BeanUtils.copyBean(cmccDaUpChannelInfoAddReq, cmccDaUpChannelInfo);
        // 渠道ID
        List<CmccDaUpChannelInfo> cmccDaUpChannelInfoList = cmccDaUpChannelInfoService
                .list(new LambdaQueryWrapper<CmccDaUpChannelInfo>().orderByDesc(CmccDaUpChannelInfo::getChannelId));
        Integer channelId = cmccDaUpChannelInfoList.get(0).getChannelId() + 1;
        cmccDaUpChannelInfo.setChannelId(channelId);
        // 字典表里创建字典数据
        SysDictData sysDictData = new SysDictData();
        SysDictData last = sysDictDataService.selectDictDataById(Long.valueOf(channelId));
        sysDictData.setDictSort(last.getDictSort() + 1);
        sysDictData.setDictLabel(cmccDaUpChannelInfo.getChannelName());
        sysDictData.setDictValue(String.valueOf(channelId));
        sysDictData.setDictType("sys_channel");
        sysDictData.setStatus("0");
        sysDictData.setIsDefault("N");
        sysDictData.setCreateBy(getUsername());
        sysDictData.setRemark("渠道信息");
        sysDictDataService.insertDictData(sysDictData);
        // 创建更新时间
        cmccDaUpChannelInfo.setCreateTime(LocalDateTime.now());
        cmccDaUpChannelInfo.setUpdateTime(LocalDateTime.now());
        // 保存
        cmccDaUpChannelInfoService.save(cmccDaUpChannelInfo);
        return success();
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/getByChannelId")
    public AjaxResult getByChannelId(@RequestBody String channelId) {
        List<CmccDaUpChannelInfo> cmccDaUpChannelInfoList = cmccDaUpChannelInfoService
                .list(new LambdaQueryWrapper<CmccDaUpChannelInfo>().eq(CmccDaUpChannelInfo::getChannelId,channelId));
        // 如果不存在则报错
        if (cmccDaUpChannelInfoList == null || cmccDaUpChannelInfoList.isEmpty()) return error("查询不到渠道信息");
        // 如果存在多条记录则bug，联系管理员
        if (cmccDaUpChannelInfoList.size() > 1) return error("当前渠道ID存在多条记录，请联系系统管理员解决");
        return success(cmccDaUpChannelInfoList.get(0));
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody @Validated CmccDaUpChannelInfoUpdateReq cmccDaUpChannelInfoUpdateReq) {
        CmccDaUpChannelInfo cmccDaUpChannelInfo = new CmccDaUpChannelInfo();
        BeanUtils.copyBean(cmccDaUpChannelInfoUpdateReq, cmccDaUpChannelInfo);
        cmccDaUpChannelInfoService.update(cmccDaUpChannelInfo,
                new LambdaUpdateWrapper<CmccDaUpChannelInfo>().eq(CmccDaUpChannelInfo::getChannelId,cmccDaUpChannelInfo.getChannelId()));
        return success();
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/del")
    public AjaxResult del(@RequestBody @NotNull Integer channelId) {
        boolean isSuccess = cmccDaUpChannelInfoService.remove(new LambdaQueryWrapper<CmccDaUpChannelInfo>().eq(CmccDaUpChannelInfo::getChannelId, channelId));
        return isSuccess ? success() : error("删除失败");
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @GetMapping("/refresh")
    public AjaxResult refresh() {
        cmccDaUpChannelInfoService.refreshChannelInfo();
        return success();
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @GetMapping("/refreshChannelCommission")
    public AjaxResult refreshChannelCommission() {
        List<CmccDaUpChannelInfo> cmccDaUpChannelInfoList = cmccDaUpChannelInfoService.list();
        cmccDaUpChannelInfoList.forEach(x -> {
            cmccDaOrderService.refreshChannelCommission(x);
        });
        return success();
    }
}
